<?php
/**
 * Created by PhpStorm.
 * User: hhlov_000
 * Date: 15-2-7
 * Time: 下午9:57
 */

namespace Home\Controller;


use Think\Controller;
use Think\Think;
use Think\Upload;

class UploadController extends Controller {

    //燕凯－－上传
    public function upload(){
        if(count($_FILES) != 1){
            $data = array('info'=>'只能导入一个文件', 'status'=>0);
            $this->ajaxReturn(json_encode($data), 'eval');
        }

        $uniqid = uniqid();
        $upload = new Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'bmp', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =      UPLOAD_PATH; // 设置附件上传根目录
        $upload->savePath  =      'images/'; // 设置附件上传（子）目录
        $upload->saveName   = $uniqid;
        // 上传文件
        $info   =   $upload->upload();
        if($info){
            $data = array('status'=>1, 'info'=>'上传成功', 'filename'=>UPLOAD_PATH.$info['photo']['savepath'].$info['photo']['savename']);
        }else{
            $data = array('status'=>0, 'info'=>$upload->getError());
        }

        //由于是通过iframe上传，部分浏览器使用json类型会直接下载文件，因此这里使用eval类型
        $this->ajaxReturn(json_encode($data), 'eval');


    }


    //dong

    /**
     * 头像上传
     */
    public function img(){
        if(!IS_POST) return false;
        $config = C('FILE_UPLOAD_CONFIG');
        $start_x = $_POST['start_x'];
        $start_y = $_POST['start_y'];
        $length_x = $_POST['length_x'];
        $length_y = $_POST['length_y'];
        return self::_xhUpload($_FILES, $config, 'img',$start_x,$start_y,$length_x,$length_y);
    }

    /**
     * 简历加项照片上传
     */
    public function photo(){
        if(!IS_POST) return false;
        $image_name = $_POST['image_name'];
        $config = C('FILE_UPLOAD_CONFIG');
        return self::_xhUploadPhoto($_FILES, $config, 'img',$image_name);
    }

    /**
     * experience附件照片上传
     */
    public function photoExp(){
        if(!IS_POST) return false;
        $exp_id = $_POST['exp_id'];
        $config = C('FILE_UPLOAD_CONFIG');
        $start_x = $_POST['start_x'];
        $start_y = $_POST['start_y'];
        $length_x = $_POST['length_x'];
        $length_y = $_POST['length_y'];
        return self::_xhUploadPhotoExp($_FILES, $config, 'img',$exp_id,$start_x,$start_y,$length_x,$length_y);
    }

    /*experience PC端附件照片上传*/
    public function photoExpPC(){
        if(!IS_POST) return false;
        $exp_id = $_POST['exp_id'];
        $config = C('FILE_UPLOAD_CONFIG');
        return self::_xhUploadPhotoExpPC($_FILES, $config, 'img',$exp_id);
    }

    /**
     * 缩略图上传
     * TODO 为了兼容不同平台，裁剪功能将在后续开发
     */
//    public function thumb(){
//        if(!IS_POST) return false;
//        $config = C('FILE_UPLOAD_IMG_CONFIG');
//        return self::_xhUpload($_FILES, $config, 'thumb');
//    }
//
//    /**
//     * flash上传
//     */
//    public function flash(){
//        if(!IS_POST) return false;
//        $config = C('FILE_UPLOAD_FLASH_CONFIG');
//        return self::_xhUpload($_FILES, $config, 'flash');
//    }

    /**
     * media上传
     */
    public function media(){
        if(!IS_POST) return false;
        $image_name = 'video_url1';
        $config = C('FILE_UPLOAD_CONFIG');
        return self::_xhUploadPhoto($_FILES, $config, 'media',$image_name);
    }

    /**
     * xheditor专用上传
     * @param string|array $files
     * @param array $config  上传配置
     * @param string $type  上传文件类型
     */
    private function _xhUpload($files, $config = array(), $type = '',$start_x,$start_y,$length_x,$length_y){
        $msg = null;
        $error = null;

        //上传配置
        $config = array_merge(C('FILE_UPLOAD_CONFIG'), $config);

        //HTML5上传
        if(isset($_SERVER['HTTP_CONTENT_DISPOSITION'])&&preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info)){
            $localName = urldecode($info[2]);
            $ext = file_ext($localName);
            if(!in_array($ext, $config['exts'])){
                $error = '上传文件后缀不允许';
            }else{
                $filename = UPLOAD_PATH . date('Y/m/d/') . uniqid() . '.' . $ext;
                $res = file_write($filename, file_get_contents("php://input"));
                if($res){
                    $msg = array(
                        'url'       => file_path2url($filename),
                        'localname' => $localName
                    );
                }else{
                    $error = '上传失败';
                }
            }
        }else{
            $upload = new \Think\Upload($config);
            $res = $upload->upload($_FILES,$config);
            if($res){
                $localName = $res['avatar']['name'];
                $filename = $res['avatar']['savepath'].$res['avatar']['savename'];
                $msg = array(
                    'url'       => file_path2url($filename),
                    'localname' => $res['avatar']['name']
                );
            }else{
                $error = $upload->getError();
            }

        }

        //针对xheditor不同上传类型返回不同结果
        if($msg){
            switch ($type){
                case 'link': //附件类型，在URL中直接显示文件名称
                    $msg['url'] .= '||' . $localName;
                    break;
            }
        }

        //裁剪压缩图片
        if( 0 != $length_x && 0 != $length_y ){
            $image_url = $msg['url'];

            $image = new \Think\Image();
            $image->open(UPLOAD_PATH.$image_url);
            $image->crop($length_x,$length_y,$start_x,$start_y)->save(UPLOAD_PATH.$image_url);
            $image->thumb(100,100)->save(UPLOAD_PATH.$image_url);
        }



        $result = json_encode(array('err'=>$error, 'msg'=>$msg));

        echo "<script>window.parent.updateImg($result);</script>";
        //返回上传结果
//        $this->ajaxReturn(json_encode(array('err'=>$error, 'msg'=>$msg)), 'eval');
    }


    /**
     * xheditor专用上传-简历加项照片一次性提交
     * @param string|array $files
     * @param array $config  上传配置
     * @param string $type  上传文件类型
     */
    private function _xhUploadPhoto($files, $config = array(), $type = '',$image_name){
        $msg = null;
        $error = null;

        //上传配置
        $config = array_merge(C('FILE_UPLOAD_CONFIG'), $config);

        //HTML5上传
        if(isset($_SERVER['HTTP_CONTENT_DISPOSITION'])&&preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info)){
            $localName = urldecode($info[2]);
            $ext = file_ext($localName);
            if(!in_array($ext, $config['exts'])){
                $error = '上传文件后缀不允许';
            }else{
                $filename = UPLOAD_PATH . date('Y/m/d/') . uniqid() . '.' . $ext;
                $res = file_write($filename, file_get_contents("php://input"));
                if($res){
                    $msg = array(
                        'url'       => file_path2url($filename),
                        'localname' => $localName
                    );
                }else{
                    $error = '上传失败';
                }
            }
        }else{
            $upload = new \Think\Upload($config);
            $res = $upload->upload($_FILES,$config);
            if($res){
                $localName = $res['avatar']['name'];
                $filename = $res['avatar']['savepath'].$res['avatar']['savename'];
                $msg = array(
                    'url'       => file_path2url($filename),
                    'localname' => $res['avatar']['name']
                );
            }else{
                $error = $upload->getError();
            }

        }

        //针对xheditor不同上传类型返回不同结果
        if($msg){
            switch ($type){
                case 'link': //附件类型，在URL中直接显示文件名称
                    $msg['url'] .= '||' . $localName;
                    break;
            }
        }

        if(!$error){
            $user_id = $_SESSION['loginUser']['user_id'];
            $resume_db = D('Resume');
            $image_url = $msg['url'];
            $resume_result = $resume_db->setResumeImg($user_id,$image_name,$image_url);
        }

        //裁剪图片
        //获取裁减参数
//        $start_x = $_POST['start_x'];
//        $start_y = $_POST['start_y'];
//        $length_x = $_POST['length_x'];
//        $length_y = $_POST['length_y'];
//
//        $image = new \Think\Image();
//        $image->open(UPLOAD_PATH.$image_url);
//        $image->crop($length_x,$length_y,$start_x,$start_y)->save($image_url);



        $result = json_encode(array('err'=>$error, 'msg'=>$msg,'result'=>$resume_result));

        echo "<script>window.parent.updateImg($result);</script>";
        //返回上传结果
//        $this->ajaxReturn(json_encode(array('err'=>$error, 'msg'=>$msg)), 'eval');
    }


    /**
     * xheditor专用上传-experience附件照片一次性提交
     * @param string|array $files
     * @param array $config  上传配置
     * @param string $type  上传文件类型
     */
    private function _xhUploadPhotoExp($files, $config = array(), $type = '',$exp_id,$start_x,$start_y,$length_x,$length_y){
        $msg = null;
        $error = null;

        //上传配置
        $config = array_merge(C('FILE_UPLOAD_CONFIG'), $config);

        //HTML5上传
        if(isset($_SERVER['HTTP_CONTENT_DISPOSITION'])&&preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info)){
            $localName = urldecode($info[2]);
            $ext = file_ext($localName);
            if(!in_array($ext, $config['exts'])){
                $error = '上传文件后缀不允许';
            }else{
                $filename = UPLOAD_PATH . date('Y/m/d/') . uniqid() . '.' . $ext;
                $res = file_write($filename, file_get_contents("php://input"));
                if($res){
                    $msg = array(
                        'url'       => file_path2url($filename),
                        'localname' => $localName
                    );
                }else{
                    $error = '上传失败';
                }
            }
        }else{
            $upload = new \Think\Upload($config);
            $res = $upload->upload($_FILES,$config);
            if($res){
                $localName = $res['avatar']['name'];
                $filename = $res['avatar']['savepath'].$res['avatar']['savename'];
                $msg = array(
                    'url'       => file_path2url($filename),
                    'localname' => $res['avatar']['name']
                );
            }else{
                $error = $upload->getError();
            }

        }

        //针对xheditor不同上传类型返回不同结果
        if($msg){
            switch ($type){
                case 'link': //附件类型，在URL中直接显示文件名称
                    $msg['url'] .= '||' . $localName;
                    break;
            }
        }
        if(!$error){
            $attachment_db = M('Attachment');
            $data['exp_id'] = $exp_id;
            $data['image_url'] = $msg['url'];
            $resume_result = $attachment_db->add($data);

        }

        //裁剪图片
        if( 0 != $length_x && 0 != $length_y ){
            $image_url = $msg['url'];

            $image = new \Think\Image();
            $image->open(UPLOAD_PATH.$image_url);
            $image->crop($length_x,$length_y,$start_x,$start_y)->save(UPLOAD_PATH.$image_url);
            $image->thumb(100,100)->save(UPLOAD_PATH.$image_url);
        }


        $result = json_encode(array('err'=>$error, 'msg'=>$msg,'result'=>$resume_result));

        echo "<script>window.parent.updateImg($result);</script>";
        //返回上传结果
//        $this->ajaxReturn(json_encode(array('err'=>$error, 'msg'=>$msg)), 'eval');
    }

    //pc端 经历上传
    private function _xhUploadPhotoExpPC($files, $config = array(), $type = '',$exp_id){
        $msg = null;
        $error = null;

        //上传配置
        $config = array_merge(C('FILE_UPLOAD_CONFIG'), $config);

        //HTML5上传
        if(isset($_SERVER['HTTP_CONTENT_DISPOSITION'])&&preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info)){
            $localName = urldecode($info[2]);
            $ext = file_ext($localName);
            if(!in_array($ext, $config['exts'])){
                $error = '上传文件后缀不允许';
            }else{
                $filename = UPLOAD_PATH . date('Y/m/d/') . uniqid() . '.' . $ext;
                $res = file_write($filename, file_get_contents("php://input"));
                if($res){
                    $msg = array(
                        'url'       => file_path2url($filename),
                        'localname' => $localName
                    );
                }else{
                    $error = '上传失败';
                }
            }
        }else{
            $upload = new \Think\Upload($config);
            $res = $upload->upload($_FILES,$config);
            if($res){
                $localName = $res['avatar']['name'];
                $filename = $res['avatar']['savepath'].$res['avatar']['savename'];
                $msg = array(
                    'url'       => file_path2url($filename),
                    'localname' => $res['avatar']['name']
                );
            }else{
                $error = $upload->getError();
            }

        }

        //针对xheditor不同上传类型返回不同结果
        if($msg){
            switch ($type){
                case 'link': //附件类型，在URL中直接显示文件名称
                    $msg['url'] .= '||' . $localName;
                    break;
            }
        }
        if(!$error){
            $attachment_db = M('Attachment');
            $data['exp_id'] = $exp_id;
            $data['image_url'] = $msg['url'];
            $resume_result = $attachment_db->add($data);

        }

        $result = json_encode(array('err'=>$error, 'msg'=>$msg,'result'=>$resume_result));

        // echo "<script>window.parent.updateImg($result);</script>";
        echo "<script>window.parent.updateExpImgPC($exp_id,$result);</script>";
        //返回上传结果
//        $this->ajaxReturn(json_encode(array('err'=>$error, 'msg'=>$msg)), 'eval');
    }


    //删除简历加项图片
    public function deletePhoto(){
        if(IS_POST){
            $resume_id = $_POST['resume_id'];
            $image_name = $_POST['image_name'];
            $image_url = $_POST['image_url'];
            $resue_db = D('Resume');
            //删除数据库数据
            $resue_result = $resue_db->deleteResumeImg($resume_id,$image_name);
            //删除后台数据
            if(is_file($image_url)){
                unlink($image_url);
            }else{

            }
            if($resue_result){
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }else{
            $this->error("错误方法");
        }
    }

    //删除附件图片
    public function deletePhotoExp(){
        if(IS_POST){
            $exp_id = $_POST['exp_id'];
            $image_url = $_POST['image_url'];
            //删除数据库数据
            $attachment_db = D('Attachment');
            $attachment_result = $attachment_db->deletePhotoExp($exp_id,$image_url);

            //删除后台数据
            if(is_file($image_url)){
                unlink($image_url);
            }else{

            }
            if($attachment_result){
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }

        }else{
            $this->error('错误方法 ');
        }
    }

    //删除视频
    public function deleteVideo(){
        if(IS_POST){
            $resume_id = $_POST['resume_id'];
            $video_url1 = 'video_url1';
            $Resume_db = D('Resume');
            $Resume_result = $Resume_db->deleteResumeVideo($resume_id);
            //删除后台数据
            if(is_file($video_url1)){
                unlink($video_url1);
            }else{

            }

            if($Resume_result){
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }else{
            $this->error(' 错误方法');
        }
    }


    //裁减图片
    public function cutImage(){
        //获取裁减参数
        $start_x = $_POST['start_x'];
        $start_y = $_POST['start_y'];
        $length_x = $_POST['length_x'];
        $length_y = $_POST['length_y'];
        $image_url = $_POST['image_url'];

        $image = new \Think\Image();
        $image->open(UPLOAD_PATH.'2015/02/15/54e0311d029c3.jpg');
        $image->crop($length_x,$length_y,$start_x,$start_y)->save($image_url);
        $this->success('成功');

    }


} 